package com.cgc.venus.server.core.aop;

import com.cgc.venus.server.core.base.BaseService;
import com.cgc.venus.server.core.utils.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 业哥 on 2017/11/22.
 */
@Aspect
@Component
public class ServiceAop {
    private Logger logger = LoggerFactory.getLogger(ServiceAop.class);
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Around("execution(public * com.cgc.venus.server.*.service.*.*(..))")
    public Object doAround(ProceedingJoinPoint pjd) throws Throwable {
        Object obj=null;
        String operObjectName="";
        String operLogParId="";
        String userId="";
        try {
            obj=pjd.getTarget();
            BaseService baseService= (BaseService) obj;
            if(StringUtil.isEmpty(baseService.getToken())){
                return handle(pjd);
            }
            operObjectName=baseService.getOperObjectName();//操作对象名称
            String className=pjd.getSignature().getDeclaringTypeName();
            String methodName=pjd.getSignature().getName();
            //用户操作日志参数id
            String sql="select id from t_oper_log_par where class_name='"+className+"' and Method_name='"+methodName+"'";
            List<Map<String, Object>> r1=jdbcTemplate.queryForList(sql);
            if(r1==null||r1.size()==0){
                return handle(pjd);
            }
            operLogParId=r1.get(0).get("id").toString();
            //获取用户id
            userId="";
            sql="select id from t_user where token='"+baseService.getToken()+"'";
            List<Map<String, Object>> r2=jdbcTemplate.queryForList(sql);
            if(r2!=null&&r2.size()>0){
                userId=r2.get(0).get("id").toString();
            }

        }catch (Exception ex){
            ex.printStackTrace();
        }
        Object result=null;
        long timeS=0;
        long timeE=0;
        String status="完成";
        int duration=0;
        try {
            timeS=System.currentTimeMillis();
            result = pjd.proceed();
            timeE=System.currentTimeMillis();
        } catch (Throwable throwable) {
            timeE=System.currentTimeMillis();
            status="失败";
            duration= (int) (timeE-timeS);
            insertOperLog(operLogParId,userId,duration,status,operObjectName);
            throw throwable;
        }
        duration= (int) (timeE-timeS);
        insertOperLog(operLogParId,userId,duration,status,operObjectName);
        return result;
    }

    /**
     * 执行方法
     * @param pjd
     * @return
     * @throws Throwable
     */
    private Object handle(ProceedingJoinPoint pjd)throws Throwable{
        return pjd.proceed();
    }

    /**
     *
     */
    private void insertOperLog(String operLogParId,String userId,int duration,String status,String operObjectName){
        try {
            String sql = "INSERT INTO t_oper_log(id,Oper_log_par,user,duration,Status,Oper_Object_name,Create_time) VALUES (?,?,?,?,?,?,NOW())";
            List<Object> objs = new ArrayList<Object>();
            objs.add(StringUtil.getUUID());
            objs.add(operLogParId);
            objs.add(userId);
            objs.add(duration);
            objs.add(status);
            objs.add(operObjectName);
            jdbcTemplate.update(sql, objs.toArray());
            //System.out.println("======插入"+r+"条操作记录=======");
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
        }
    }
}
